package com.eyeem.recyclerviewtools.sample;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.ButtonBarLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.eyeem.recyclerviewtools.ItemOffsetDecoration;
import com.eyeem.recyclerviewtools.LoadMoreOnScrollListener;
import com.eyeem.recyclerviewtools.OnItemClickListener;
import com.eyeem.recyclerviewtools.RecyclerViewTools;
import com.eyeem.recyclerviewtools.StaggeredLayoutManagerUtils;
import com.eyeem.recyclerviewtools.adapter.WrapAdapter;
import com.eyeem.recyclerviewtools.sample.adapter.DataAdapter;
import com.eyeem.recyclerviewtools.sample.adapter.Sections;
import com.eyeem.recyclerviewtools.sample.data.Config;
import com.eyeem.recyclerviewtools.sample.data.Data;
import com.eyeem.recyclerviewtools.sample.data.Photo;
import com.eyeem.recyclerviewtools.sample.widget.Header;
import com.squareup.picasso.Picasso;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by budius on 26.05.16.
 */
public class SampleActivity extends BaseActivity implements Toolbar.OnMenuItemClickListener,
        LoadMoreOnScrollListener.Listener,
        OnItemClickListener/*,StickyHeaderHandler*/ {
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.recycler)
    RecyclerView recycler;
    @Nullable
    @Bind(R.id.refresh)
    SwipeRefreshLayout refresh;
    @Nullable
    @Bind(R.id.header_image)
    ImageView header;

    private View customView;
    private DataAdapter adapter;
    private WrapAdapter wrapAdapter;
    CollapsingToolbarLayoutState state = CollapsingToolbarLayoutState.EXPANDED;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Config config = (Config) getIntent().getSerializableExtra(Config.TAG);

        setContentView(config.useCoordinatorLayout ? R.layout.activity_sample_swipe : R.layout.activity_sample);
        if (config.userHeaderImage) {
            //请在layout根节点设置：android:fitsSystemWindows="true"
            // inflate and bind
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            // getWindow().setStatusBarColor(Color.TRANSPARENT);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        } else {
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
        }

        ButterKnife.bind(this);
        //显示返回按钮:
//        setSupportActionBar(toolbar);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // Toolbar
        toolbar.setTitle("Hello Droids!");
        toolbar.inflateMenu(R.menu.menu);
        toolbar.setOnMenuItemClickListener(this);
        toolbar.setNavigationIcon(R.mipmap.back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //toolbar.setLogo(R.drawable.header);
        // SwipeRefreshLayout
        if (refresh != null && header != null) {
            Picasso.with(this)
                    .load(Photo.HEADER(getResources().getDisplayMetrics().widthPixels))
                    .fit().centerCrop().into(header);

            dismissRefresh(refresh);
        }
        if (config.useCoordinatorLayout) {
            final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbarLayout);
            final ButtonBarLayout playButton = (ButtonBarLayout) findViewById(R.id.playButton);
            final AppBarLayout appbar = (AppBarLayout) findViewById(R.id.appbar);
            //以下AppBarLayout代码参考http://www.jianshu.com/p/06c0ae8d9a96
            //AppBarLayout
            appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
                @Override
                public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                    if (verticalOffset == 0) {
                        if (state != CollapsingToolbarLayoutState.EXPANDED) {
                            state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                            collapsingToolbarLayout.setTitle("EXPANDED");//设置title为EXPANDED
                        }
                    } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                        if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                            collapsingToolbarLayout.setTitle("");//设置title不显示
                            playButton.setVisibility(View.VISIBLE);//隐藏播放按钮
                            state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                        }
                    } else {
                        if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                            if (state == CollapsingToolbarLayoutState.COLLAPSED) {
                                playButton.setVisibility(View.GONE);//由折叠变为中间状态时隐藏播放按钮
                            }
                            collapsingToolbarLayout.setTitle("INTERNEDIATE");//设置title为INTERNEDIATE
                            state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                        }
                    }
                }
            });
            collapsingToolbarLayout.setExpandedTitleGravity(Gravity.CENTER);
            collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER);
        }
        // Adapter
        adapter = DataAdapter.generateRandom(this);
        if (config.useSections) {
            wrapAdapter = new WrapAdapter(adapter, new Sections());
        } else {
            wrapAdapter = new WrapAdapter(adapter);
        }

        // Layout manager
        RecyclerView.LayoutManager layoutManager;
        switch (config.layoutManager) {
            case Config.GRID_LAYOUT_MANAGER:
                layoutManager = new GridLayoutManager(this, config.layoutManagerSpan);
                ((GridLayoutManager) layoutManager).setSpanSizeLookup(wrapAdapter.createSpanSizeLookup(config.layoutManagerSpan));
                break;
            case Config.STAGGERED_GRID_LAYOUT_MANAGER:
                layoutManager = new StaggeredGridLayoutManager(config.layoutManagerSpan, StaggeredGridLayoutManager.VERTICAL);
                break;
            /*case Config.LINEAR_LAYOUT_STICKY_MANAGER:
                layoutManager = new StickyLayoutManager(this, this);
                compileItems();
                break;*/
            case Config.LINEAR_LAYOUT_MANAGER:
            default:
                layoutManager = new LinearLayoutManager(this);
                break;
        }
        recycler.setLayoutManager(layoutManager);
        recycler.setAdapter(wrapAdapter);

        // Header
        if (config.useHeader) {
            wrapAdapter.addHeader(new Header(this));
        }

        // Load more scroller
        if (config.useLoadMore) {
            recycler.addOnScrollListener(new LoadMoreOnScrollListener(this));
        }

        // OnItemClickListener
        if (config.useOnItemClick) {
            wrapAdapter.setOnItemClickListener(recycler, this);
        }

        if (config.useItemOffsetDecoration) {
            float dpi = getResources().getDisplayMetrics().density;
            int internalOffset = (int) dpi * 4;
            int externalOffset = (int) dpi * 24;
            recycler.addItemDecoration(new ItemOffsetDecoration(
                    // around the item views - similar to recyclerView.setPadding(...)
                    externalOffset,
                    externalOffset / 2,
                    externalOffset,
                    0,
                    // in-between views - similar to holder.itemView.setPadding(...)
                    internalOffset,
                    internalOffset,
                    internalOffset,
                    internalOffset,
                    true
            ));
        }
    }

//    /**
//     * 监听返回按钮的点击事件
//     *
//     * @param item
//     * @return
//     */
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case android.R.id.home:
//                finish();
//                break;
//        }
//        return super.onOptionsItemSelected(item);
//    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_item_scroll_to_top:
                RecyclerViewTools.fastScrollToTop(recycler);
                toast("Fast Scroll to Top");
                return true;
            case R.id.menu_item_toggle_custom_view:
                item.setChecked(!item.isChecked());
                item.setIcon(item.isChecked() ?
                        R.drawable.ic_check_box_white_24dp :
                        R.drawable.ic_check_box_outline_blank_white_24dp);
                setCustomView(item.isChecked());
            default:
                return false;
        }
    }

    @Override
    public void onLoadMore(RecyclerView recyclerView) {
        //toast("Load more");
        wrapAdapter.showLoadMore();
        recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {

                for (int i = 0; i < 5; i++) {
                    adapter.data.add(Data.newRandom(SampleActivity.this));
                }

                if (recycler.getLayoutManager() instanceof StaggeredGridLayoutManager) {
                    StaggeredLayoutManagerUtils.onItemChanged(recycler, 0);
                }
                adapter.notifyDataSetChanged();
                wrapAdapter.hideLoadMore();

            }
        }, 1000);
    }

    @Override
    public void onItemClick(RecyclerView parent, View view, int position, long id, RecyclerView.ViewHolder viewHolder) {
        popView(view, position);
    }

    private void popView(View view, int position) {
        fancyAnimation(view);
        toast("Clicked position " + position);
    }

    private void setCustomView(boolean visible) {
        if (visible && customView == null) {
            customView = LayoutInflater.from(this)
                    .inflate(R.layout.custom_view, recycler, false);
        }
        wrapAdapter.setCustomView(visible ? customView : null);
        if (visible) {
            toast("Custom view on WrapAdapter");
        }

    }

    public enum CollapsingToolbarLayoutState {
        EXPANDED, COLLAPSED, INTERNEDIATE;
    }


}
